package com.dc.server.threadpool;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


public class ThreadPoolManager {
	private final static int CORE_POOL_SIZE = 10;
	//TODO 这个值需要优化
	private final static int MAXIMUM_POOL_SIZE = Integer.MAX_VALUE;
	private final static int KEEP_ALIVE_TIME = 60;
	private static ExecutorService instance = null;

	private static final Logger logger = LoggerFactory.getLogger(ThreadPoolManager.class);


	public static synchronized ExecutorService newInstance(){
//		if(null == instance){
//			instance = Executors.newCachedThreadPool();
//		}
//		return instance;
		return getInstance();
	}

	public static synchronized ExecutorService getInstance(){
		if(null == instance){
			instance = new ThreadPoolExecutor(CORE_POOL_SIZE,MAXIMUM_POOL_SIZE,
					KEEP_ALIVE_TIME, TimeUnit.SECONDS,new SynchronousQueue<Runnable>());
		}
		return instance;
	}

	/**
	 * 最大线程池统计打印信息
	 * */
	static{
		ThreadPoolExecutor executor = (ThreadPoolExecutor)getInstance();
		Thread printThread = new Thread(new Runnable(){
			@Override
			public void run() {
				while(true){
					try {
						//5分钟打印一次
						Thread.sleep(5*60*1000L);
						//Thread.sleep(5*1000L);
						logger.warn("Thread pool info: [CORE_POOL_SIZE="+ executor.getCorePoolSize()
								+ "; MAXIMUM_POOL_SIZE=" + executor.getMaximumPoolSize()
								+ "; BlockingQueue_SIZE=" + executor.getQueue().size()
								+ "; CURRENT_THREADS=" + executor.getPoolSize()
								+ "; LARGEST_POOL_SIZE=" + executor.getLargestPoolSize()
								+ "] \n\r" + executor.toString());

					} catch (InterruptedException e) {
						//e.printStackTrace();
					}
				}
			}
		});
		printThread.start();
	}

}
